package com.loong.web.suppert.intercept.checkpoint;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.loong.tool.lang.Requests;
import com.loong.tool.lang.Strings;

/**
 * 访问检测器
 *
 * @author 张成轩
 */
public class CheckpointController {

	private String regex_ip;
	private String regex_url;
	private String regex_param;

	/** 恶意请求处理器 */
	private MaliciousHandler maliciousHandler;

	/**
	 * @param request 请求
	 * @param response 响应
	 * @return 是否为恶意请求
	 * @throws IOException IO异常
	 */
	public boolean control(HttpServletRequest request, HttpServletResponse response) throws IOException {

		if (Strings.isNotNull(regex_ip) && Requests.getIp(request).matches(regex_ip)) {
			if (maliciousHandler != null)
				maliciousHandler.ip(request, response);
			return false;
		}
		if (Strings.isNotNull(regex_url) && request.getServletPath().toLowerCase().matches(regex_url)) {
			if (maliciousHandler != null)
				maliciousHandler.url(request, response);
			return false;
		}
		if (Strings.isNotNull(regex_param) && request.getQueryString() != null
				&& request.getQueryString().toLowerCase().matches(regex_param)) {
			if (maliciousHandler != null)
				maliciousHandler.param(request, response);
			return false;
		}
		return true;
	}

	/**
	 * @param maliciousHandler 恶意请求处理器
	 */
	public void setMaliciousHandler(MaliciousHandler maliciousHandler) {

		this.maliciousHandler = maliciousHandler;
	}

	/**
	 * @param regex_ip 黑名单正则表达式
	 */
	public void setRegex_ip(String regex_ip) {

		this.regex_ip = regex_ip;
	}

	/**
	 * @param regex_url 恶意url正则表达式
	 */
	public void setRegex_url(String regex_url) {

		this.regex_url = regex_url;
	}

	/**
	 * @param regex_param 恶意参数正则表达式
	 */
	public void setRegex_param(String regex_param) {

		this.regex_param = regex_param;
	}
}
